﻿/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.VisualBasic;
using Votations.NSurvey.Enums;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Web;


namespace Votations.NSurvey.WebAdmin
{
    /// <summary>
    /// Edit a matrix question type
    /// </summary>
    public partial class EditMatrixQuestion : PageBase
    {


        protected void Page_Load(object sender, System.EventArgs e)
        {
            SetupSecurity();
            ValidateRequestParentQuestionId();
            LocalizePage();
            MessageLabel.Visible = false;
            if (!Page.IsPostBack)
            {
                BindQuestionOptions();
                BindChildQuestions();
                BindAnswerOptions();
            }
        }

        private void SetupSecurity()
        {
            CheckRight(NSurveyRights.AccessFormBuilder, true);
        }

        private void LocalizePage()
        {
            EditMatrixQuestionTitle.Text = GetPageResource("EditMatrixQuestionTitle");
            MultipleChoicesMatrixLabel.Text = GetPageResource("MultipleChoicesMatrixLabel");
            AnswerRatingLabel.Text = GetPageResource("AnswerRatingLabel");
            MinSelectionLabel.Text = GetPageResource("MinSelectionLabel");
            MaxSelectionAllowed.Text = GetPageResource("MaxSelectionAllowed");
            UpdateQuestionButton.Text = GetPageResource("UpdateQuestionButton");
            InsertNewTitle.Text = GetPageResource("InsertNewTitle");
            RowLabel.Text = GetPageResource("RowLabel");
            ExportXMLButton.Text = GetPageResource("ExportXMLButton");
            ColumnLabel.Text = GetPageResource("ColumnLabel");
            AddColumnButton.Text = GetPageResource("AddColumnButton");
            AddRowButton.Text = GetPageResource("AddRowButton");
            CurrentRowsColumnsTitle.Text = GetPageResource("CurrentRowsColumnsTitle");
            ((BoundColumn)RowsDataGrid.Columns[0]).HeaderText = GetPageResource("RowsHeader");
            ((EditCommandColumn)RowsDataGrid.Columns[1]).UpdateText = GetPageResource("UpdateRowTextHeader");
            ((EditCommandColumn)RowsDataGrid.Columns[1]).CancelText = GetPageResource("CancelRowTextHeader");
            ((EditCommandColumn)RowsDataGrid.Columns[1]).EditText = GetPageResource("EditRowTextHeader");
            ((ButtonColumn)RowsDataGrid.Columns[2]).Text = GetPageResource("DeleteRowText");

            ((BoundColumn)ColsDataGrid.Columns[0]).HeaderText = GetPageResource("AnswerHeader");
            ((TemplateColumn)ColsDataGrid.Columns[1]).HeaderText = GetPageResource("ColTypeHeader");
            ((TemplateColumn)ColsDataGrid.Columns[2]).HeaderText = GetPageResource("ColRatingHeader");
            ((EditCommandColumn)ColsDataGrid.Columns[3]).UpdateText = GetPageResource("UpdateColTextHeader");
            ((EditCommandColumn)ColsDataGrid.Columns[3]).CancelText = GetPageResource("CancelColTextHeader");
            ((EditCommandColumn)ColsDataGrid.Columns[3]).EditText = GetPageResource("EditColTextHeader");
            ((ButtonColumn)ColsDataGrid.Columns[4]).Text = GetPageResource("DeleteColText");

            if (!Page.IsPostBack)
            {
                MinSelectionDropDownList.Items.Insert(0, new ListItem(GetPageResource("NoSelectionRequiredOption"), "0"));
                MaxAllowedDropDownList.Items.Insert(0, new ListItem(GetPageResource("UnlimitedSelectionOption"), "0"));
            }

        }

        private void ValidateRequestParentQuestionId()
        {
            _parentQuestionId =
                Information.IsNumeric(Request["ParentQuestionId"]) ? int.Parse(Request["ParentQuestionId"]) : -1;

            if (_parentQuestionId != -1 && !NSurveyUser.Identity.IsAdmin &&
                !NSurveyUser.Identity.HasAllSurveyAccess)
            {
                if (!new Question().CheckQuestionUser(_parentQuestionId, NSurveyUser.Identity.UserId))
                {
                    _parentQuestionId = -1;
                }
            }


            if (_parentQuestionId == -1)
            {
                throw new FormatException("Invalid matrix question id!");
            }
        }



        /// <summary>
        /// Set the forms to match DB question options
        /// </summary>
        private void BindQuestionOptions()
        {
            // Retrieve the original question values
            QuestionData question = new Questions().GetQuestionById(_parentQuestionId);
            QuestionData.QuestionsRow questionRow = question.Questions[0];

            // Assign them to the form
            QuestionFreeTextBox.Text = questionRow.QuestionText;
            MinSelectionDropDownList.SelectedValue =
                (questionRow.IsMinSelectionRequiredNull()) ? "0" : questionRow.MinSelectionRequired.ToString();
            MaxAllowedDropDownList.SelectedValue =
                (questionRow.IsMaxSelectionAllowedNull()) ? "0" : questionRow.MaxSelectionAllowed.ToString();

            MultipleChoiceCheckbox.Checked = questionRow.SelectionModeId == (int)QuestionSelectionMode.MultiMatrix;
            RatingCheckbox.Checked = questionRow.RatingEnabled;
            ViewState["LibrayID"] = questionRow.IsLibraryIdNull() ? -1 : questionRow.LibraryId;

            if (!questionRow.IsLibraryIdNull() && !NSurveyUser.Identity.IsAdmin)
            {
                CheckRight(NSurveyRights.ManageLibrary, true);
            }

        }

        private void BindChildQuestions()
        {
            MatrixChildQuestionData childQuestions = new MatrixChildQuestionData();
            childQuestions = new Questions().GetMatrixChildQuestions(_parentQuestionId);
            RowsDataGrid.DataSource = childQuestions;
            RowsDataGrid.DataMember = "ChildQuestions";
            RowsDataGrid.DataKeyField = "QuestionID";
            RowsDataGrid.DataBind();
        }

        private void BindAnswerOptions()
        {
            _answerTypes = new AnswerTypes().GetAnswerTypes();
            AnswerTypeDropDownList.DataSource = _answerTypes;
            AnswerTypeDropDownList.DataMember = "AnswerTypes";
            AnswerTypeDropDownList.DataTextField = "Description";
            AnswerTypeDropDownList.DataValueField = "AnswerTypeID";
            AnswerTypeDropDownList.DataBind();
            TranslateListControl(AnswerTypeDropDownList);
            AnswerTypeDropDownList.Items.Insert(0,
                new ListItem(GetPageResource("SelectTypeMessage"), "-1"));
            AnswerTypeDropDownList.SelectedValue = "1";
            _answers = new Answers().GetAnswers(_parentQuestionId);
            ColsDataGrid.Columns[2].Visible = RatingCheckbox.Checked;
            ColsDataGrid.DataSource = _answers;
            ColsDataGrid.DataMember = "Answers";
            ColsDataGrid.DataKeyField = "AnswerId";
            ColsDataGrid.DataBind();
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.RowsDataGrid.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.RowsDataGrid_CancelCommand);
            this.RowsDataGrid.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.RowsDataGrid_EditCommand);
            this.RowsDataGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.RowsDataGrid_UpdateCommand);
            this.RowsDataGrid.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.RowsDataGrid_DeleteCommand);
            this.ColsDataGrid.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.ColsDataGrid_CancelCommand);
            this.ColsDataGrid.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.ColsDataGrid_EditCommand);
            this.ColsDataGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.ColsDataGrid_UpdateCommand);
            this.ColsDataGrid.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.ColsDataGrid_DeleteCommand);
            this.ColsDataGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.ColsDataGrid_ItemDataBound);

        }
        #endregion

        private void RowsDataGrid_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            RowsDataGrid.EditItemIndex = e.Item.ItemIndex;
            BindChildQuestions();
        }

        private void RowsDataGrid_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            RowsDataGrid.EditItemIndex = -1;
            BindChildQuestions();
        }

        private void RowsDataGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {

            TextBox updatedChildText = ((TextBox)e.Item.Cells[0].Controls[0]);
            if (updatedChildText.Text.Length == 0)
            {
                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("RowMissingQuestionMessage");
            }
            else
            {
                MatrixChildQuestionData childQuestion = new MatrixChildQuestionData();
                MatrixChildQuestionData.ChildQuestionsRow updatedChildQuestion =
                childQuestion.ChildQuestions.NewChildQuestionsRow();
                updatedChildQuestion.QuestionId =
                    int.Parse(RowsDataGrid.DataKeys[e.Item.ItemIndex].ToString());
                updatedChildQuestion.QuestionText = updatedChildText.Text;
                childQuestion.ChildQuestions.AddChildQuestionsRow(updatedChildQuestion);
                new Question().UpdateChildQuestion(childQuestion);
                RowsDataGrid.EditItemIndex = -1;
                BindChildQuestions();
                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("MatrixRowUpdatedMessage");
            }
        }

        private void RowsDataGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            new Question().DeleteQuestionById(
                int.Parse(RowsDataGrid.DataKeys[e.Item.ItemIndex].ToString()));
            BindChildQuestions();
            MessageLabel.Visible = true;
            MessageLabel.Text = GetPageResource("MatrixRowDeletedMessage");

        }

        protected void AddRowButton_Click(object sender, System.EventArgs e)
        {
            if (NewRowTextBox.Text.Length == 0)
            {
                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("RowMissingQuestiondMessage");
            }
            else
            {
                MatrixChildQuestionData childQuestion = new MatrixChildQuestionData();
                MatrixChildQuestionData.ChildQuestionsRow updatedChildQuestion =
                    childQuestion.ChildQuestions.NewChildQuestionsRow();
                updatedChildQuestion.ParentQuestionId = _parentQuestionId;
                updatedChildQuestion.QuestionText = NewRowTextBox.Text;
                childQuestion.ChildQuestions.AddChildQuestionsRow(updatedChildQuestion);
                new Question().AddChildQuestion(childQuestion);

                BindChildQuestions();
                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("MatrixRowAddedMessage");

                NewRowTextBox.Text = string.Empty;
            }
        }

        protected void UpdateQuestionButton_Click(object sender, System.EventArgs e)
        {
            if (QuestionFreeTextBox.Text.Length == 0)
            {
                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("MissingQuestionMessage");
            }
            else
            {
                // creates a BE and update the question
                QuestionData question = new QuestionData();
                QuestionData.QuestionsRow updatedQuestion =
                    question.Questions.NewQuestionsRow();

                // Set the updated fields
                updatedQuestion.QuestionId = _parentQuestionId;
                updatedQuestion.SurveyId = SurveyId;
                updatedQuestion.QuestionText = QuestionFreeTextBox.Text.Length > 3900 ?
                    QuestionFreeTextBox.Text.Substring(0, 3900) : QuestionFreeTextBox.Text;
                updatedQuestion.MinSelectionRequired = int.Parse(MinSelectionDropDownList.SelectedValue);
                updatedQuestion.MaxSelectionAllowed = int.Parse(MaxAllowedDropDownList.SelectedValue);
                updatedQuestion.RatingEnabled = RatingCheckbox.Checked;
                updatedQuestion.RandomizeAnswers = false;
                if (MultipleChoiceCheckbox.Checked)
                {
                    updatedQuestion.SelectionModeId = (int)QuestionSelectionMode.MultiMatrix;
                }
                else
                {
                    updatedQuestion.SelectionModeId = (int)QuestionSelectionMode.Matrix;
                }

                question.Questions.AddQuestionsRow(updatedQuestion);

                new Question().UpdateQuestion(question);

                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("OptionsUpdatedMessage");
                BindQuestionOptions();
                BindAnswerOptions();
            }

        }

        protected void AddColumnButton_Click(object sender, System.EventArgs e)
        {
            if (AnswerTypeDropDownList.SelectedValue == "-1")
            {
                MessageLabel.Text = GetPageResource("MissingTypeMessage");
                MessageLabel.Visible = true;
            }
            else
            {

                AnswerData answer = new AnswerData();
                AnswerData.AnswersRow newAnswer = answer.Answers.NewAnswersRow();

                newAnswer.QuestionId = _parentQuestionId;
                newAnswer.AnswerText = NewColumnTextBox.Text;
                newAnswer.AnswerTypeId =
                    int.Parse(AnswerTypeDropDownList.SelectedValue);
                answer.Answers.AddAnswersRow(newAnswer);

                new Answer().AddMatrixAnswer(answer);

                MessageLabel.Visible = true;
                MessageLabel.Text = GetPageResource("MatrixColumnAddedMessage");

                NewColumnTextBox.Text = string.Empty;
                BindAnswerOptions();
            }
        }


        private void ColsDataGrid_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            DataGridItem gridItem = (DataGridItem)e.Item;
            ColsDataGrid.EditItemIndex = gridItem.ItemIndex;

            // Rebind the answers
            BindAnswerOptions();

            // Enable the dropdownlist 
            DropDownList currentAnswerTypes =
                (DropDownList)ColsDataGrid.Items[gridItem.ItemIndex].Cells[1].Controls[1];
            currentAnswerTypes.Enabled = true;

            CheckBox ratingCheckBox =
                (CheckBox)ColsDataGrid.Items[gridItem.ItemIndex].Cells[3].FindControl("RatingPartCheckBox");

            ratingCheckBox.Enabled = true;
        }


        private void ColsDataGrid_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            ColsDataGrid.EditItemIndex = -1;
            BindAnswerOptions();

        }

        /// <summary>
        /// Generates the templated column with the
        /// selection mode
        /// </summary>
        private void ColsDataGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            DataGridItem gridItem = (DataGridItem)e.Item;
            if (gridItem.ItemType != ListItemType.Footer && gridItem.ItemType != ListItemType.Header)
            {
                DropDownList answerTypesDropDownList =
                    (DropDownList)gridItem.Cells[1].Controls[1];
                answerTypesDropDownList.DataSource = _answerTypes;
                answerTypesDropDownList.DataMember = "AnswerTypes";
                answerTypesDropDownList.DataTextField = "Description";
                answerTypesDropDownList.DataValueField = "AnswerTypeID";
                answerTypesDropDownList.DataBind();
                TranslateListControl(answerTypesDropDownList);

                answerTypesDropDownList.Enabled = false;
                answerTypesDropDownList.SelectedValue =
                    _answers.Answers[gridItem.DataSetIndex].AnswerTypeId.ToString();

                int typeMode = int.Parse(DataBinder.Eval(e.Item.DataItem, "TypeMode").ToString());
                bool ratePart = (bool)DataBinder.Eval(gridItem.DataItem, "RatePart");
                CheckBox ratingPartCheckBox = (CheckBox)gridItem.FindControl("RatingPartCheckBox");

                // Can this answer be rated ?
                if ((((AnswerTypeMode)typeMode & AnswerTypeMode.Selection) > 0))
                {
                    ratingPartCheckBox.Visible = true;
                    if (ratePart)
                    {
                        ((Label)gridItem.FindControl("RatingLabel")).Text = _currentRating.ToString();
                        ratingPartCheckBox.Checked = true;
                        _currentRating++;
                    }
                    else
                    {
                        ((Label)gridItem.FindControl("RatingLabel")).Text = "0";
                    }
                }
                else
                {
                    ratingPartCheckBox.Visible = false;
                    ratingPartCheckBox.Checked = false;
                }

            }

        }


        /// <summary>
        /// Updates the columns
        /// </summary>
        private void ColsDataGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            DataGridItem gridItem = (DataGridItem)e.Item;
            AnswerData answer = new AnswerData();

            AnswerData.AnswersRow updatedAnswer = answer.Answers.NewAnswersRow();

            updatedAnswer.AnswerText = ((TextBox)gridItem.Cells[0].Controls[0]).Text;
            updatedAnswer.AnswerTypeId =
                int.Parse(((DropDownList)gridItem.Cells[1].Controls[1]).SelectedValue);
            updatedAnswer.AnswerId = int.Parse(ColsDataGrid.DataKeys[gridItem.ItemIndex].ToString());
            updatedAnswer.RatePart = ((CheckBox)gridItem.Cells[2].FindControl("RatingPartCheckBox")).Checked;
            answer.Answers.AddAnswersRow(updatedAnswer);

            new Answer().UpdateMatrixAnswer(answer);

            ColsDataGrid.EditItemIndex = -1;
            BindAnswerOptions();

            MessageLabel.Visible = true;
            MessageLabel.Text = GetPageResource("MatrixColumnUpdatedMessage");

        }

        /// <summary>
        /// Deletes the answer column
        /// </summary>
        private void ColsDataGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            new Answer().DeleteMatrixAnswer(
                int.Parse(ColsDataGrid.DataKeys[e.Item.ItemIndex].ToString()));

            MessageLabel.Visible = true;
            MessageLabel.Text = GetPageResource("MatrixColumnDeletedMessage");
            BindAnswerOptions();
        }

        protected void ExportXMLButton_Click(object sender, System.EventArgs e)
        {
            Response.Charset = "utf-8";
            Response.ContentType = "application/octet-stream";

            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_question" + _parentQuestionId + ".xml\"");

            NSurveyQuestion questionForm = new Questions().GetQuestionForExport(_parentQuestionId);
            questionForm.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);
            Response.End();
        }


        int _parentQuestionId,
            _currentRating = 1;
        AnswerTypeData _answerTypes;
        AnswerData _answers;

    }

}
